package com.alibaba.filter;

import com.alibaba.common.ResponseResult;
import com.alibaba.domain.LoginUser;
import com.alibaba.fastjson.JSON;
import com.alibaba.utils.JwtUtil;
import com.alibaba.utils.RedisCache;
import com.alibaba.utils.WebUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

import static com.alibaba.common.SystemConstants.REDIS_KEY_PREFIX;
import static com.alibaba.define.enums.AppHttpCodeEnum.NEED_LOGIN;

/**
 * @author : hanyang
 * @date : 2023-11-04 10:35
 **/

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头中的token
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        // 解析获取userId
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            log.info("doFilterInternal Exception e:{}", JSON.toJSONString(e));
            // token超时
            // token非法
            ResponseResult<Object> error = ResponseResult.error(NEED_LOGIN.getCode(), NEED_LOGIN.getMsg());
            WebUtils.renderString(httpServletResponse, JSON.toJSONString(error));
            return;
        }
        String userId = claims.getSubject();
        // 从redis中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject(REDIS_KEY_PREFIX + userId);
        if (Objects.isNull(loginUser)) {
            ResponseResult<Object> error = ResponseResult.error(NEED_LOGIN.getCode(), NEED_LOGIN.getMsg());
            WebUtils.renderString(httpServletResponse, JSON.toJSONString(error));
            return;
        }
        // 存入SecurityContextHolder
        // 将Authentication对象存入SecurityContextHolder的主要原因是为了让Spring Security的授权机制能够在后续的过程中使用这个对象来检查用户是否具有执行当前请求所需的权限。
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
